import jwt
import json
import datetime
from jwt import exceptions
from backend.settings import SECRET_KEY
from system.models import *


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)


def create_token(payload):
    # 声明类型，声明加密算法
    headers = {
        "type": "jwt",
        "alg": "HS256"
    }
    # 设置过期时间
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
    result = jwt.encode(payload=payload, key=SECRET_KEY, algorithm="HS256", headers=headers)
    # 返回加密结果
    return result


def parse_payload(token):
    # 自定义对象
    message = {"code": 200, "data": None, "msg": "操作成功"}
    try:
        # 进行解密
        verified_payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        cache_token = Token.objects.filter(userId=verified_payload['userId']).first()
        cache_token.token = cache_token.token.replace('Bearer ', "")
        if token != cache_token.token:
            message['code'] = 400
            message['msg'] = "token已失效，请重新登录"
        user = Users.objects.filter(id=verified_payload['userId']).first()
        if user.status == 2:
            message['code'] = 400
            message['msg'] = "该账号已被禁用，请联系管理员"
        if user.identity == 2:
            message['code'] = 400
            message['msg'] = "您暂时没有操作权限"
        # 返回结果
        message['data'] = verified_payload
    except exceptions.ExpiredSignatureError:
        message['code'] = 400
        message['msg'] = "token已过期或失效"
    except jwt.DecodeError:
        message['code'] = 400
        message['msg'] = "身份认证失败，token有误"
    except jwt.InvalidTokenError:
        message['code'] = 400
        message['msg'] = "token格式不正确，非法的token"
    return message
